package login;

import java.io.*;
import java.util.ArrayList;

/**
 * Created by dllo on 18/4/16.
 */


public class IOUtils {

    public static final String FILE_NAME = "user.txt"; // 创建一个常量

    /**
     * 存储用户信息
     *
     * @param user 要存储的用户信息
     */
    public static void saveUser(User user) {  // 写流方法
        File file = new File(FILE_NAME); // 查询这个文件
        OutputStream os = null; // 输出流=空

        try {
            if (!file.exists()) { // 判断这个文件是否存在
                file.createNewFile(); // 不存在建一个文件
            }
            os = new FileOutputStream(file,true); // 打开file这个文件的输出流
            String userInfo = user.getUsername() + ":" + user.getPwd() + ";";
            os.write(userInfo.getBytes()); // 写流

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            closeAll(os);
        }
    }

    public static ArrayList<User> initUsers() {  // 读流方法
        ArrayList<User> users = new ArrayList<>();
        File file = new File(FILE_NAME);
        if (!file.exists()) {
            return users;
        }
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            byte[] buff = new byte[1024];
            int pos = 0;
            StringBuilder builder = new StringBuilder();
            while ((pos = is.read(buff)) != -1) {
                String s = new String(buff, 0, pos);
                builder.append(s);
            }
            String data = builder.toString();

            String[] userInfos = data.split(";"); // 拆分
            for (String userInfo : userInfos) {
                String[] info = userInfo.split(";");
                User user = new User();
                user.setUsername(info[0]);
                user.setPwd(info[1]);
                users.add(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll(is);
        }
        return users;
    }

    public static void closeAll(Closeable... closeables) { // 关流方法
        if (closeables == null) {
            return;
        }
        for (Closeable closeable : closeables) {
            if (closeable != null) {
                try {
                    closeable.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
